package com.springboot.springbootlogindemo.utils;

import org.apache.commons.io.FileUtils;
import org.lionsoul.ip2region.xdb.Searcher;

import java.io.File;
import java.text.MessageFormat;
import java.util.Objects;

public class AddressUtil {

    /**
     * 当前记录地址的本地DB
     */
    private static final String TEMP_FILE_DIR = "/home/admin/app/";

    /**
     * 根据IP地址查询登录来源
     *
     * @param ip
     * @return
     */
    public static String getCityInfo(String ip) {
        try {
            // 获取当前记录地址位置的文件
            String dbPath = Objects.requireNonNull(AddressUtil.class.getResource("/ip2region/ip2region.xdb")).getPath();
            File file = new File(dbPath);
            //如果当前文件不存在，则从缓存中复制一份
            if (!file.exists()) {
                dbPath = TEMP_FILE_DIR + "ip.db";
                System.out.println(MessageFormat.format("当前目录为:[{0}]", dbPath));
                file = new File(dbPath);
                FileUtils.copyInputStreamToFile(Objects.requireNonNull(AddressUtil.class.getClassLoader().getResourceAsStream("classpath:ip2region/ip2region.xdb")), file);
            }
            //创建查询对象
            Searcher searcher = Searcher.newWithFileOnly(dbPath);
            //开始查询

           // String address =  searcher.searchByStr(ip).replaceAll("[^\u4E00-\u9FA5]", "");
           // return searcher.searchByStr(ip).replaceAll("[^\u4E00-\u9FA5]", "");
            return getAddress(searcher.searchByStr(ip));
        } catch (Exception e) {
            e.printStackTrace();
        }
        //默认返回空字符串
        return "";
    }

    private static int indexOfTarget(String source, String target, int n) {
        int index = source.indexOf(target);
        int i = 0;
        while (index != -1) {
            index = source.indexOf(target, index + i);
            i++;
            if (i == n) {
                break;
            }
        }
        return index;
    }

    private static String getAddress(String address){
        int first=indexOfTarget(address,"|",2);
        int second=indexOfTarget(address,"|",3);
        int third=indexOfTarget(address,"|",4);
        StringBuilder sb=new StringBuilder();
        sb.append(address.substring(first+1,second));
        sb.append(address.substring(second+1,third));
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(getCityInfo("112.10.180.1"));
    }
}